<?php

namespace app\index\controller\gupiao;

use think\Controller;
use app\index\controller\Base;
use think\Db;


class Users extends Base
{
    
    /**
     * 个人信息
     * URL :index/gupiao.users/personalInfo
     * @return [type] [description]
     */
    public function personalInfo()
    {
    	// 授权验证
    	if(!$this->uid){
    		return json([
                    'code'      => 400,
                    'dest'      => '缺少code'
                ]);
    	}
    	$user_info = Db('users')
            ->field('name,photo,sex,introduce,balance,is_manager')
            ->where('id',$this->uid)
            ->find();
    	if($user_info){
    		// 输出
	        return json([
	                'code'          => 200,
	                'dest'          => 'success',
	                'data'          => $user_info
	            ]);
    	}else{
    		return json([
                    'code'      => 400,
                    'dest'      => '缺少code'
                ]);
    	}
    }


    /**
     * 交易记录
     * URL :index/gupiao.users/record
     * @return [type] [description]
     */
    public function record()
    {
        // 授权验证
        if(!$this->uid){
            return json([
                    'code'      => 400,
                    'dest'      => '缺少code'
                ]);
        }

        $page       = input('page')     ? input('page')     : 1;                                   // 页码
        $pageSize   = input('limit')    ? input('limit')    : config('paginate')['list_rows'];     // 每页显示条数

        // 管理员 -- 查询所有记录
        if($this->admin == 1){
            $list = Db('orders')
                    ->field('order_id,username,photo,live_name,create_time,amount')
                    ->where('status',1)
                    ->where('amount','gt',0)
                    ->order('update_time desc')
                    ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                    ->toArray();
        // 用户数据
        }else{
            $list = Db('orders')
                    ->field('order_id,username,photo,live_name,create_time,amount')
                    ->where('uid',$this->uid)
                    ->where('status',1)
                    ->where('amount','gt',0)
                    ->order('update_time desc')
                    ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                    ->toArray();
        }

        // 输出数据
        if($list){
            foreach ($list['data'] as $key => $value) {
                $list['data'][$key]['create_time'] = date("m-d H:i",$value['create_time']);
            }
            return json([
                    'code'          => 200,
                    'dest'          => 'success',
                    'count'         => $list['total'],
                    'data'          => $list['data']
                ]);
        }else{
            return json([
                    'code'      => 400,
                    'dest'      => '暂无交易记录'
                ]);
        }

    }


    /**
     * 充值记录
     * URL :index/gupiao.users/rechargeList
     * @return [type] [description]
     */
    public function rechargeList()
    {
        // 授权验证
        if(!$this->uid){
            return json([
                    'code'      => 400,
                    'dest'      => '缺少code'
                ]);
        }


        $page       = input('page')     ? input('page')     : 1;                                   // 页码
        $pageSize   = input('limit')    ? input('limit')    : config('paginate')['list_rows'];     // 每页显示条数

        // 管理员 -- 查询所有记录
        if($this->admin == 1){
            $list = Db('recharge')
                    ->field('order_id,money,username,create_time,photo')
                    ->where('status',1)
                    ->order('create_time desc')
                    ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                    ->toArray();
            // 用户数据
        }else{
            $list = Db('recharge')
                    ->field('order_id,money,username,create_time,photo')
                    ->where('uid',$this->uid)
                    ->where('status',1)
                    ->order('create_time desc')
                    ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                    ->toArray();
        }

        // 输出数据
        if($list){
            foreach ($list['data'] as $key => $value) {
                $list['data'][$key]['create_time'] = date("y-m-d H:i",$value['create_time']);
            }
            return json([
                    'code'          => 200,
                    'dest'          => 'success',
                    'count'         => $list['total'],
                    'data'          => $list['data']
                ]);
        }else{
            return json([
                    'code'      => 400,
                    'dest'      => '暂无交易记录'
                ]);
        }
    }


    /**
     * 用户充值
     * URL :index/gupiao.users/recharge
     * @return [type] [description]
     */
    // 用户充值可以判断有没输入金额  没有输入就使用默认
    public function recharge()
    {
        // 授权验证
        if(!$this->uid>1){
            return json([
                    'code'      => 400,
                    'dest'      => '未获取到用户信息'
                ]);
        }

        // 充值金额
        $money      = input('money');
        if($money<=0){
            return json([
                    'code'      => 400,
                    'dest'      => '充值金额非法'
                ]);
        }

        // 入库参数整理
        $params['uid']          = $this->uid;
        $params['username']     = $this->username;
        $params['photo']        = $this->photo;
        $params['money']        = $money;
        $params['order_id']     = time().rand(10000,99999);
        $params['create_time']  = time();

        $re = Db('recharge')->insert($params);

        // 数据返回
        if($re){

            return json([
                    'code'      => 200,
                    'dest'      => 'success',
                    'data'      => $this->pay($params['order_id'],$money,$this->request->domain()."/index/pay/WxReturnRecharge",'余额充值'),
                    'order_id'  => $params['order_id']
                ]);

        }else{
            return json([
                    'code'      => 400,
                    'dest'      => '下单失败，请重试！',
                    'data'      => []
                ]);
        }

    }




    /**
     * 微信支付
     * @return [type] [description]
     */
    public function pay($order_id,$amount,$call_back='',$note='余额充值')
    {
        // 授权验证
        if(!$this->uid){
            return json([
                    'code'      => 400,
                    'dest'      => '缺少code'
                ]);
        }

        // 用户openid
        $openid = Db('users')->where('id',$this->uid)->value('openid');
        if(!$openid){
            return json([
                    'code'      => 400,
                    'dest'      => '用户信息错误'
                ]);
        }

        // 验证订单有效性
        $order_info = Db('recharge')->where('order_id',$order_id)->find();
        if(!$order_info || $order_info['status'] != 0){
            return json([
                    'code'      => 400,
                    'dest'      => '订单信息有误或已经支付',
                    'data'      => []
                ]);
        }

        // 统一下单
        header('Content-Type:text/html;charset=UTF-8');

        // 导入微信支付sdk
        Vendor('Weixinpay.WxPayConfig');
        Vendor('Weixinpay.WxPayApi');
        Vendor('Weixinpay.JsApiPay');
        Vendor('Weixinpay.WxPayResults');

        $tools = new \JsApiPay();

        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($note);
        $input->SetAttach("test");
        $input->SetOut_trade_no($order_id);
        $input->SetTotal_fee($amount*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url($call_back);
        $input->SetTrade_type("JSAPI");

        $input->SetOpenid($openid);

        $order = \WxPayApi::unifiedOrder($input);

        $jsApiParameters = $tools->GetJsApiParameters($order);
        //获取共享收货地址js函数参数
        $editAddress = $tools->GetEditAddressParameters();

        return $jsApiParameters;

    }





    /**
     * 订单状态验证
     * URL:index/gupiao.users/checkRecharge
     */
    public function checkRecharge()
    {
        $order_id   = input('order_id');
        $info = Db('recharge')->field('order_id,status')->where('order_id',$order_id)->find();
        return json([
                    'code'          => 200,
                    'dest'          => 'success',
                    'data'          => $info
                ]);

    }


    /**
     * 用户信息编辑
     * URL:index/gupiao.users/editUserInfo
     */
    public function editUserInfo()
    {
        // 授权验证
        if(!$this->uid){
            return json([
                    'code'      => 400,
                    'dest'      => '缺少code'
                ]);
        }
        
        $data = [];
        
        // 更新数据
        input('tel')        == null || $data['tel']         = input('tel');
        input('name')       == null || $data['name']        = input('name');
        input('ID_card')    == null || $data['ID_card']     = input('ID_card');
        input('sex')        == null || $data['sex']         = input('sex');
        input('age')        == null || $data['age']         = input('age');
        input('introduce')  == null || $data['introduce']   = input('introduce');

        // 更新字段验证
        if($data == ''){
            return json([
                    'code'      => 400,
                    'dest'      => '暂无数据更新'
                ]);
        }

        // 更新
        $re = Db('users')->where('id',$this->uid)->update($data);
        if($re){
            return json([
                    'code'      => 200,
                    'dest'      => '用户信息已更新'
                ]);
        }else{
            return json([
                    'code'      => 400,
                    'dest'      => '暂无数据更新'
                ]);
        }

    }



}
